<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: xajax.products_images.php 432 2014-01-19 11:46:17Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 432 $
* 	zuletzt geaendert von:	$Author: siekiera $
* 	Datum:					$Date: 2014-01-19 11:46:17 +0000 (Sun, 19 Jan 2014) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright (c) since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */

defined('_VALID_XTC') or die('Direct Access to this location is not allowed.');

require_once(DIR_FS_INC.'inc.get_url_friendly_text.php');
require_once(DIR_FS_INC.'inc.get_img_alt.php');

$xajax->registerFunction('generateImages');
$xajax->registerFunction('generateMoreImages');
$xajax->registerFunction('deleteImage');
$xajax->registerFunction('FirstImg');
$xajax->registerFunction('MoreImg');
$xajax->registerFunction('openInputForUrl');
$xajax->registerFunction('getURLPreview');
$xajax->registerFunction('deleteTempImage');
$xajax->registerFunction('saveURLPreview');
$xajax->registerFunction('dialog');

function generateImages($pname, $pid) {
	global $db, $catfunc;
	
	$ajax = new xajaxResponse();

	$getName = $db->db_query("SELECT
									products_name
								FROM
									".TABLE_PRODUCTS_DESCRIPTION."
								WHERE
									products_id = '".(int)$pid."'
								AND
									language_id = '".$_SESSION['languages_id']."'");
	
	$pname_arr = explode('.', $pname);
	$nsuffix = array_reverse($pname_arr);

	if(IMAGE_NAME_PRODUCT == 'p_id') {
		$new_products_name = $pid.'.'.strtolower($nsuffix[0]);
	} elseif(IMAGE_NAME_PRODUCT == 'p_name') {
		if(file_exists(DIR_FS_CATALOG_ORIGINAL_IMAGES.get_url_friendly_text($getName->fields['products_name']).'.'.$nsuffix[0]))
			$new_products_name = get_url_friendly_text($getName->fields['products_name']).'-'.$pid.'.'.$nsuffix[0];
		else
			$new_products_name = get_url_friendly_text($getName->fields['products_name']).'.'.$nsuffix[0];
		
	} else
		$new_products_name = get_url_friendly_text($pname_arr[0]).'.'.strtolower($nsuffix[0]);
	
	$products_image_name = $new_products_name;
	if(!file_exists(DIR_FS_CATALOG_ORIGINAL_IMAGES.$products_image_name))
		@rename(DIR_FS_CATALOG_ORIGINAL_IMAGES.$pname, DIR_FS_CATALOG_ORIGINAL_IMAGES.$products_image_name);
	else
		copy(DIR_FS_CATALOG_ORIGINAL_IMAGES.$pname, DIR_FS_CATALOG_ORIGINAL_IMAGES.$products_image_name);

  $image_paths = getImagePaths(DIR_FS_CATALOG_PRODUCTS_IMAGES, 'DIR_FS_CATALOG');
  foreach($image_paths as $image_path) {
    if ($image_path != 'original_images') {
      $parameter_path = explode('_', $image_path);
      $parameter_path = 'product_image_'.$parameter_path[0];
      processImages(
        DIR_FS_CATALOG_ORIGINAL_IMAGES,
        constant('DIR_FS_CATALOG_'.strtoupper($image_path)),
        $products_image_name, strtoupper($parameter_path));
    }
  }
/*
	require(DIR_WS_INCLUDES.'product_icon_images.php');
	require(DIR_WS_INCLUDES.'product_thumbnail_images.php');
	require(DIR_WS_INCLUDES.'product_info_images.php');
	require(DIR_WS_INCLUDES.'product_popup_images.php');
*/	
	$db->db_query("UPDATE ".TABLE_PRODUCTS." SET products_image = '".$products_image_name."' WHERE products_id = ".$db->db_prepare($pid));
	
	$ajax->call('xajax_FirstImg', $pid);
	$ajax->script('msg(\'success\',\'Erfolgreich gespeichert\',\'Das Produktbild wurde erfolgreich gespeichert\');');

	return $ajax;
}

function generateMoreImages($pname, $pid) {
	global $db, $catfunc;
	
	$ajax = new xajaxResponse();

	$getName = $db->db_query("SELECT
									products_name
								FROM
									".TABLE_PRODUCTS_DESCRIPTION."
								WHERE
									products_id = ".$db->db_prepare($pid)."
								AND
									language_id = '".(int)$_SESSION['languages_id']."'");
	
	$nextNr = $db->db_query("SELECT
									image_nr
								FROM
									".TABLE_PRODUCTS_IMAGES."
								WHERE
									products_id = ".$db->db_prepare($pid)."
								ORDER BY
									image_nr DESC
								LIMIT 1");
	
	$pname_arr = explode('.', $pname);
	$nsuffix = array_reverse($pname_arr);
	$next_nr = $nextNr->fields['image_nr']+1;
	if(IMAGE_NAME_PRODUCT == 'p_id') {
		$new_products_name = $pid.'-'.$next_nr.'.'.strtolower($nsuffix[0]);
	} elseif(IMAGE_NAME_PRODUCT == 'p_name') {
		if(file_exists(DIR_FS_CATALOG_ORIGINAL_IMAGES.get_url_friendly_text($getName->fields['products_name']).'-'.$next_nr.'.'.$nsuffix[0]))
			$new_products_name = get_url_friendly_text($getName->fields['products_name']).'-'.$next_nr.'-'.$pid.'.'.$nsuffix[0];
		else
			$new_products_name = get_url_friendly_text($getName->fields['products_name']).'-'.$next_nr.'.'.$nsuffix[0];
	} else
		$new_products_name = get_url_friendly_text($pname_arr[0]).'-'.$next_nr.'.'.strtolower($nsuffix[0]);

	$products_image_name = $new_products_name;
	if(!file_exists(DIR_FS_CATALOG_ORIGINAL_IMAGES.$products_image_name))
		@rename(DIR_FS_CATALOG_ORIGINAL_IMAGES.$pname, DIR_FS_CATALOG_ORIGINAL_IMAGES.$products_image_name);
	else
		copy(DIR_FS_CATALOG_ORIGINAL_IMAGES.$pname, DIR_FS_CATALOG_ORIGINAL_IMAGES.$products_image_name);

  $image_paths = getImagePaths(DIR_FS_CATALOG_PRODUCTS_IMAGES, 'DIR_FS_CATALOG');
  foreach($image_paths as $image_path) {
    if ($image_path != 'original_images') {
      $parameter_path = explode('_', $image_path);
      $parameter_path = 'product_image_'.$parameter_path[0];
      processImages(
        DIR_FS_CATALOG_ORIGINAL_IMAGES,
        constant('DIR_FS_CATALOG_'.strtoupper($image_path)),
        $products_image_name, strtoupper($parameter_path));
    }
  }
/*
	require(DIR_WS_INCLUDES.'product_icon_images.php');
	require(DIR_WS_INCLUDES.'product_thumbnail_images.php');
	require(DIR_WS_INCLUDES.'product_info_images.php');
	require(DIR_WS_INCLUDES.'product_popup_images.php');
*/	
	$img_arr = array('products_id' => $pid,
						'image_nr' => $next_nr,
						'image_name' => $products_image_name);
	$db->db_perform(TABLE_PRODUCTS_IMAGES, $img_arr);

	$ajax->call('xajax_MoreImg', $pid, $next_nr);
	$ajax->script('msg(\'success\',\'Erfolgreich gespeichert\',\'Das Produktbild wurde erfolgreich gespeichert\');');
	
	return $ajax;
}

function deleteImage($pname, $pid, $img_nr = '') {
	global $db;
	
	$ajax = new xajaxResponse();

	if(empty($img_nr))
		$db->db_query("UPDATE ".TABLE_PRODUCTS." SET products_image = '' WHERE products_id = ".$db->db_prepare($pid));
	else
		$db->db_query("DELETE FROM ".TABLE_PRODUCTS_IMAGES." WHERE products_id = ".$db->db_prepare($pid)." AND image_nr = ".$db->db_prepare($img_nr));
		
	@unlink(DIR_FS_CATALOG_ORIGINAL_IMAGES.$pname);
	@unlink(DIR_FS_CATALOG_THUMBNAIL_IMAGES.$pname);
	@unlink(DIR_FS_CATALOG_ICON_IMAGES.$pname);
	@unlink(DIR_FS_CATALOG_INFO_IMAGES.$pname);
	@unlink(DIR_FS_CATALOG_POPUP_IMAGES.$pname);
	
	if(empty($img_nr)) {
		$ajax->remove('pi_'.$pid);
		$ajax->script('uploadFirst()');
	} else
		$ajax->remove('pi_'.$pid.'_'.$img_nr);
	$ajax->script('msg(\'success\',\'Erfolgreich gelöscht\',\'Das Produktbild wurde aus dem Shop gelöscht\');');
	return $ajax;
}

function FirstImg($pid) {
	global $db;
	
	$ajax = new xajaxResponse();
	
	$img = $db->db_query("SELECT products_image FROM ".TABLE_PRODUCTS." WHERE products_id = ".$db->db_prepare($pid));
	if ($img->_numOfRows && !empty($img->fields['products_image'])) {
		$languages = get_languages();
		$p = '	<div id="pi_'.$pid.'" class="dn">
					<table width="100%">
						<tr>
							<td align="left" class="main" width="'.(PRODUCT_IMAGE_THUMBNAIL_WIDTH + 15).'">
								'.image(DIR_WS_CATALOG_THUMBNAIL_IMAGES.$img->fields['products_image'], 'Hauptbild').'<br /><br />
								<a href="#" class="button" onclick="return ask(\''.ASK_CONFIRM_DELETE_IMAGE.'\',\''.$img->fields['products_image'].'\','.$pid.')">'.TEXT_DELETE.'</a>
							</td>
							
							<td class="main">
								<b>'.$img->fields['products_image'].'</b><br /><br />
								Alternativtext:<br />';
								for($i = 0, $n = sizeof($languages); $i < $n; $i++) {
									$p .= '	<nobr>
												'.image(DIR_WS_LANGUAGES.$languages[$i]['directory'] .'/'. $languages[$i]['image'], $languages[$i]['name']).' '.draw_input_field('products_image_alt_'.$languages[$i]['id'], get_img_alt((int)$pid, $languages[$i]['id']), 'style="width:90%"').'
											</nobr><br />';
								}
		$p .= 		'		</td>
						</tr>
					</table>
				</div><br />';
	
		$ajax->assign('product_image', 'innerHTML', $p);
		$ajax->script('$("#pi_'.$pid.'").animate({opacity:"+=0"},2100).fadeIn()');

	} else
		$ajax->script('uploadFirst()');
	
	return $ajax;
}

function MoreImg($pid, $img_nr) {
	global $db;
	
	$ajax = new xajaxResponse();
	
	$img = $db->db_query("SELECT 
								image_name 
							FROM 
								".TABLE_PRODUCTS_IMAGES." 
							WHERE 
								products_id = ".$db->db_prepare($pid)." 
							AND 
								image_nr = ".$db->db_prepare($img_nr));

	if ($img->_numOfRows) {
		$languages = get_languages();
		$p = '	<div id="pi_'.$pid.'_'.$img_nr.'" class="dn" style="margin-bottom:10px">
					<table width="100%">
						<tr>
							<td align="left" class="main" width="'.(PRODUCT_IMAGE_THUMBNAIL_WIDTH + 15).'">
								'.image(DIR_WS_CATALOG_THUMBNAIL_IMAGES.$img->fields['image_name'], 'Standard Image').'
							</td>
							
							<td class="main">
								<b>'.$img->fields['image_name'].'</b><br />
								<a href="javascript:void(0)" class="button" onclick="return ask(\''.ASK_CONFIRM_DELETE_IMAGE.'\', \''.$img->fields['image_name'].'\','.$pid.','.$img_nr.');">'.TEXT_DELETE.'</a><br /><br />
								Alternativtext:<br />';
								for($i = 0, $n = sizeof($languages); $i < $n; $i++) {
									$p .= '	<nobr>
												'.image(DIR_WS_LANGUAGES . $languages[$i]['directory'] .'/'. $languages[$i]['image'], $languages[$i]['name']).' '.draw_input_field('products_image_alt_'.$languages[$i]['id'], get_img_alt((int)$pid, $languages[$i]['id']), 'style="width:90%"').'
											</nobr><br />';
								}
		$p .= 		'		</td>
						</tr>
					</table>
				</div>';
		
		$ajax->append('products_images', 'innerHTML', $p);
		$ajax->script('$("#pi_'.$pid.'_'.$img_nr.'").animate({opacity:"+=0"},200).fadeIn();');
	}
	
	return $ajax;
}

function openInputForUrl(){
	$ajax = new xajaxResponse();
	
	$c  = draw_input_field('img_url', '', 'class="img_url" style="width:98%" autocomplete="off"').'<br />';
	$c .= '<button class="button get_img_url" type="submit">Grafik anzeigen</button>';
	
	$ajax->call('xajax_dialog', $c, 'URL zur Grafik', '400', '110');
	
	return $ajax;
}

function getURLPreview($val, $id) {
	$ajax = new xajaxResponse();
	
	$content = @file_get_contents($val);
	
	$cache_name = end(explode('/', $val));
	
	$fp = fopen(DIR_FS_CATALOG_ORIGINAL_IMAGES.$cache_name, 'w');
	fwrite($fp, $content);
	fclose($fp);
	
	if(isset($content)){
		$c = "<div style=\"text-align:center\"><img src=\"".DIR_WS_CATALOG_ORIGINAL_IMAGES.$cache_name."\" alt=\"\" style=\"max-height:300px;max-width:300px\"><br><button class=\"button\" type=\"submit\" onclick=\"xajax_saveURLPreview(\'".$cache_name."\',".$id.")\">Grafik speichern</button><button class=\"button\" type=\"button\" onclick=\"xajax_deleteTempImage(\'".$cache_name."\')\">Abbruch, Grafik löschen</button></div>";
		
	} else
		$c = 'Da stimmt was nicht. Es ist ein Fehler aufgetreten.';
	
	$ajax->call('xajax_dialog', $c, 'Ist das die gewünschte Grafik?', '400', '400');
	
	return $ajax;
}

function saveURLPreview($name, $id) {
	global $db;
	
	$ajax = new xajaxResponse();
	
	$check = $db->db_query("SELECT 
								products_image
							FROM
								".TABLE_PRODUCTS."
							WHERE
								products_id = '".(int)$id."'");
		
	if(empty($check->fields['products_image']))
		$ajax->call('xajax_generateImages', $name, (int)$id);
	else
		$ajax->call('xajax_generateMoreImages', $name, (int)$id);
	
	$ajax->script('$(\'.ui-dialog-content\').dialog(\'close\');');
	
	return $ajax;
}

function deleteTempImage($n) {
	$ajax = new xajaxResponse();

	unlink(DIR_FS_CATALOG_ORIGINAL_IMAGES.$n);	
	$ajax->call('xajax_dialog', 'Die temporäre Grafik wurde verworfen', 'Gelöscht', '250', '130');
	
	return $ajax;
}